﻿function getToken() {
    var token = getCookie("token")
    if(token.length > 0){
        return token;
    }else{
        return "{登录后可见}"
    }
}



function getGuestUid() {
    var guestUid = getCookie("guestUid");
    //if(guestUid.length == 0){
        var date = new Date();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();
        var milliseconds = date.getMilliseconds();
        guestUid =  minutes+""+seconds +""+milliseconds;
        setCookie("guestUid",guestUid)
    //}
    return guestUid;
}

function initToast() {
    toastr.options = {
        "closeButton": false,
        "debug": false,
        "newestOnTop": false,
        "progressBar": true,
        "positionClass": "toast-top-center",
        "preventDuplicates": true,
        "onclick": null,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": "2000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    }

}

function getServerName() {
    return config.api;
}

var postting = false;
var posttime = 0;
function startPost(){
    postting = true;
    posttime = new Date().getTime()
    $("#loading").show()
    $("#loading").css("width",20+"%")
}
function stopPost(){
    postting = false;
    posttime = 0;
    $("#loading").hide()
}
function isposting(){
	if(postting &&  new Date().getTime()-posttime < 1000 ){
		return true
	}else{
		return false;
	}
}


/**
 *    侦查附件上传情况,这个方法大概0.05-0.1秒执行一次
 */
function progressBar(evt) {
    var loaded = evt.loaded; //已经上传大小情况
    var tot = evt.total; //附件总大小
    var per = Math.floor(100 * loaded / tot); //已经上传的百分比
    $("#loading").css("width",per+"%")
    //$.fn.progressInit.draw(per + '%'); //绘制经度条
}

$(document).ready(function() {
	$("#header").load('header.html');
	$("#logo").load('logo.html');
	$("#footer").load('footer.html',function () {
        LoadCountData();
    });

});

function setCookie(name,value){
	name = "u1rl_cn_"+name
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*30);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}

function getCookie(name){
    name = "u1rl_cn_"+name
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return "";
}

function CheckPassword() {
	if (!CheckInput("passwordInput", /^\d{4}$/, "亲，必须4位数字"))
		return;
	var password = $("#passwordInput").val();
	if (!isposting()) {
        startPost();
		var item={};
		item.password=password;
		item.id=$("#id").val()
		PostServerData("url/checkurl", JSON.stringify(item), function(rd) {
			stopPost();
			if (rd.code == 0) {
				window.location = rd.data.longUrl;
			} else {
				CheckInput("passwordInput", /^\w{9}$/, "密码不正确");
			}
		});
	}
}

function SubmitClick() {
	if (!isposting()) {
		var url = encodeURI($("#longurl").val());
		if (!CheckLongurl(url))
			return;
        startPost();
		PostServerData("url/add", {
			"longurl" : url
		}, function(rd) {
            stopPost();
			ShowResult(rd,"");
		});
	}
}

function ProSubmitClick() {
	if (!isposting()) {
		var url = encodeURI($("#longurl").val());
		var tip="";
		if (!CheckLongurl(url))
			return;
		if ($("input[name=timeRadios]:checked").val() == 1 && !CheckInput("timeInput", /^\d{1,3}$/, "亲，必须1-3位数字"))
			return;
		if ($("input[name=countRadios]:checked").val() == 1 && !CheckInput("countInput", /^\d{1,8}$/, "亲，必须1-8位数字"))
			return;
		if ($("input[name=passwordRadios]:checked").val() == 1 && !CheckInput("passwordInput", /^\d{4}$/, "亲，必须4位数字"))
			return;
		if ($("input[name=tareaRadios]:checked").val() == 1) {
			if (!CheckInput("tareaInput", /^\d{1,2}-\d{1,2}$/, "亲，必须形如0-24"))
				return;
			else {
				var vv = $("#tareaInput").val();
				var arr = vv.split("-");
				if (arr[0] > arr[1] || arr[0] > 23 || arr[1] > 24) {
					$("#tareaInput").focus();
					$("#tareaInput").css("border", "1px solid red");
					var d = dialog({
						quickClose : true,
						content : "亲，时段必须在0-24之间。"
					});
					d.show(document.getElementById("tareaInput"));
					return;
				}
			}
		}
        startPost();
		var item = {};
		item.longurl = url;
		item.timeCount = $("#timeInput").val();
		item.timeUnit = $("#timeUnit").val();
		item.count = $("#countInput").val();
		item.countUnit = $("#countUnit").val();
		item.password = $("#passwordInput").val();
		item.tarea = $("#tareaInput").val();
		item.timezone = $("#timeZone").val();
		if(item.timeCount!="") tip+="@有效期:"+item.timeCount+item.timeUnit;
		if(item.count!="") tip+=" @限制访问:"+item.count+item.countUnit;
		if(item.password!="") tip+=" @访问密码:"+item.password;
		if(item.tarea!="") tip+=" @可访问时段:"+item.tarea;
		PostServerData("url/eadd", JSON.stringify(item), function(rd) {
            stopPost();
			// $("input[name=timeRadios]").eq(0).trigger("click");
			// $("input[name=countRadios]").eq(0).trigger("click");
			// $("input[name=passwordRadios]").eq(0).trigger("click");
			//$("input[name=tareaRadios]").eq(0).trigger("click");
			ShowResult(rd,tip);
		});
	}
}

function ShowResult(rd,tip) {
	var data = rd.data.d;
    var serverName = getServerName();
	data= data.replace(":80/","/")
    serverName= serverName.replace(":80","")
	if (data != "") {
		var xhtml = "";
		xhtml += "<div><span style='font-weight:bold;'>短链详情：</span><span>"+tip+"</span></div><div class='input-append'><input id='shorturl' type='text' class='span3' value='" + data + "'><button class='btn btn-primary' type='button' data-clipboard-target='#shorturl'>复制</button></div>";
		xhtml += "<div><span style='font-weight:bold;'>二维码：</span><span id='code'></span></div>";
		xhtml += "<div style='padding-top:10px;'><span style='float:left;'>&nbsp;&nbsp;&nbsp;&nbsp;分享：</span><span class=\"bdsharebuttonbox\"><a href=\"#\" class=\"bds_more\" data-cmd=\"more\"></a><a href=\"#\" class=\"bds_weixin\" data-cmd=\"weixin\" title=\"分享到微信\"></a><a href=\"#\" class=\"bds_sqq\" data-cmd=\"sqq\" title=\"分享到QQ好友\"></a><a href=\"#\" class=\"bds_tsina\" data-cmd=\"tsina\" title=\"分享到新浪微博\"></a><a href=\"#\" class=\"bds_qzone\" data-cmd=\"qzone\" title=\"分享到QQ空间\"></a><a href=\"#\" class=\"bds_tqq\" data-cmd=\"tqq\" title=\"分享到腾讯微博\"></a><a href=\"#\" class=\"bds_renren\" data-cmd=\"renren\" title=\"分享到人人网\"></a><a href=\"#\" class=\"bds_fbook\" data-cmd=\"fbook\" title=\"分享到Facebook\"></a></span></div>";
		xhtml += "<script>";
		xhtml += "window._bd_share_config = {";
		xhtml += "\"common\": {";
		xhtml += "\"bdSnsKey\": {},";

        xhtml += "\"bdText\": \"永久免费短链接在线生成网站"+serverName+"\",";
		xhtml += "\"bdDesc\": \"永久免费短链接在线生成网站"+serverName+"\",";
		xhtml += "\"bdUrl\":\"" + data + "\",";
		xhtml += "\"bdMini\": \"2\",";
		xhtml += "\"bdMiniList\": false,";
		xhtml += "\"bdPic\": \"\",";
		xhtml += "\"bdStyle\": \"0\",";
		xhtml += "\"bdSize\": \"16\"";
		xhtml += "},";
		xhtml += "\"share\": {}";
		xhtml += "};";
		xhtml += "with (document) 0[(getElementsByTagName('head')[0] || body).appendChild(createElement('script')).src = 'http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion=' + ~(-new Date() / 36e5)];";
		xhtml += "</script>";

		var sdialog = dialog({
			title : serverName+' 永久免费',
			content : xhtml,
			onclose : function() {
				//$("#longurl").val("");
				LoadCountData();
			}
		});
		sdialog.showModal();
		$("#code").qrcode({
			width : 300,
			height : 300,
			render : "table",
			text : data
		});
		var clipboard = new ClipboardJS('.btn.btn-primary');

		clipboard.on('success', function(e) {
			/*var d = dialog({
				onshow : function() {
					setTimeout(function() {
						d.close().remove()
					}, 1000);
				},
				content : "复制成功"
			});
			d.show();*/
			showSuccess("复制成功")
			e.clearSelection();
		});

		clipboard.on('error', function(e) {
			console.error('Action:', e.action);
			console.error('Trigger:', e.trigger);
		});
	}
}

function CheckLongurl(url) {
	if (typeof (url) == "undefined" || url == "" || !IsURL(url)) {
		$("#longurl").focus();
		$("#longurl").css("border", "1px solid red");
		// var d = dialog({
		// 	onshow : function() {
		// 		setTimeout(function() {
		// 			d.close().remove()
		// 		}, 1000);
		// 	},
		// 	content : "亲，请输入正确的网址哦。"
		// });
		// d.show();
		showWarning("亲，请输入正确的网址哦。")
		return false;
	}
	$("#longurl").css("border", "");
	return true;
}

function CheckInput(id, pattern, tip) {
	var vv = $("#" + id).val();
	console.log(vv);
	if (pattern.test(vv) && vv != "") {
		$("#" + id).css("border", "");
		return true;
	}
	$("#" + id).focus();
	$("#" + id).css("border", "1px solid red");
	var d = dialog({
		quickClose : true,
		content : tip
	});
	d.show(document.getElementById(id));
	return false;
}

function checkLogin() {
    if(getCookie("token").length == 0){
        showWarning("请先登录")
        setTimeout(function () {
            location.href = "login.html?message=请先登录"
        },2000)

        return false;
    }else{
    	return true;
	}
}
function EnableInput(id, dvalue) {
	$("#" + id).prop("disabled", "");
	$("#" + id).focus();
	$("#" + id).val(dvalue);
}

function DisableInput(id) {
	//$("#" + id).val("");
	$("#" + id).prop("disabled", "disabled");
}

function LoadCountData() {
	PostServerData("url/count", {}, function(rd) {
		$("#num1").html(fmoney(rd.data.today_add));
		$("#num2").html(fmoney(rd.data.today_get));
		$("#num3").html(fmoney(rd.data.total_add));
		$("#num4").html(fmoney(rd.data.total_get));
	});
}

function showMsg(msg) {
    var d = dialog({
        onshow : function() {
            setTimeout(function() {
                d.close().remove()
            }, 1000);
        },
        content : msg
    });
    d.show();
	
}

function showSuccess(msg) {
    initToast()
    toastr["success"](msg)
}
function showWarning(msg) {
    initToast()
    toastr["warning"](msg)
}
function showError(msg) {
    initToast()
    toastr["error"](msg)
}

function SubmitReport() {
	var url = encodeURI($("#badurl").val());
	if (url == "" || !IsURL(url)) {
		$("#badurl").focus();
		$("#badurl").css("border", "1px solid red");
		showWarning("亲，请输入正确的网址哦。")
		return;
	}
	$("#badurl").css("border", "");
	var name = $("#zname").val();
	var contact = $("#zaddress").val();
	if (!isposting()) {
        startPost();
		PostServerData("report/add", JSON.stringify({
            "url" : url,
            "name" : name,
            "contact" : contact
        }), function(rd) {
            stopPost();
			$("#badurl").val("");
			if (rd.code == 0) {
				/*var d = dialog({
					onshow : function() {
						setTimeout(function() {
							d.close().remove()
						}, 3000);
					},
					content : "提交已成功,我们会尽快审核,再次感谢您！"
				});
				d.show();*/
				showSuccess("提交已成功,我们会尽快审核,再次感谢您！")
			}
		});
	}
}

/**
 * 登录
 * @constructor
 */
function SubmitLogin() {
	$("#loginFormBtn").prop("disabled", "disabled");
    var username = $("#username").val();
    var password = $("#password").val();
    if (username == "") {
        $("#username").focus();
        $("#username").css("border", "1px solid red");
        showWarning("亲，请输入用户名哦。")
        $("#loginFormBtn").prop("disabled", "");
        return;
    }
    if (password == "") {
        $("#password").focus();
        $("#password").css("border", "1px solid red");
        showWarning("亲，请输入密码哦。")
        $("#loginFormBtn").prop("disabled", "");
        return;
    }
    $("#username").css("border", "");
    $("#password").css("border", "");
    if (!isposting()) {
        startPost();
        PostServerData("user/login", JSON.stringify({
            "username" : username,
            "password" : password
        }), function(rd) {
            stopPost();
            $("#loginFormBtn").prop("disabled", "");
            if (rd.code == 0) {
                var id = rd.data.id
                var username = rd.data.username
                var nickname = rd.data.nickname
                var token = rd.data.token
                setCookie("id",id)
                setCookie("username",username)
                setCookie("nickname",nickname)
                setCookie("token",token)
                showSuccess("登录成功！正在跳转...")
                setTimeout(function () {
                    location.href = './'
                },2000)
            }else{
            	var message = rd.message
                showWarning(message)
			}
        });
    }
}

/**
 * 注册
 * @constructor
 */
function SubmitRegister() {
    $("#registerFormBtn").prop("disabled", "disabled");
    var username = $("#username").val();
    var password = $("#password").val();
    var passwordConfirm = $("#passwordConfirm").val();
    if (username == "") {
        $("#username").focus();
        $("#username").css("border", "1px solid red");
        showWarning("亲，请输入用户名哦。")
        $("#registerFormBtn").prop("disabled", "");
        return;
    }
    if (password == "") {
        $("#password").focus();
        $("#password").css("border", "1px solid red");
        showWarning("亲，请输入密码哦。")
        $("#registerFormBtn").prop("disabled", "");
        return;
    }
    if (passwordConfirm == "") {
        $("#passwordConfirm").focus();
        $("#passwordConfirm").css("border", "1px solid red");
        showWarning("亲，请输入确认密码哦。")
        $("#registerFormBtn").prop("disabled", "");
        return;
    }
    if(password != passwordConfirm){
        $("#passwordConfirm").focus();
        $("#passwordConfirm").css("border", "1px solid red");
        showWarning("亲， 两次输入密码不一致哦。")
        $("#registerFormBtn").prop("disabled", "");
        return;
	}
    $("#username").css("border", "");
    $("#password").css("border", "");
    $("#passwordConfirm").css("border", "");
    if (!isposting()) {
        startPost();
        $("#registerFormBtn").prop("disabled", "");
        PostServerData("user/register", JSON.stringify({
            "username" : username,
            "password" : password,
            "passwordConfirm" : passwordConfirm
        }), function(rd) {
            stopPost();
            if (rd.code == 0) {
            	var id = rd.data.id
            	var username = rd.data.username
            	var nickname = rd.data.nickname
            	var token = rd.data.token
				setCookie("id",id)
				setCookie("username",username)
				setCookie("nickname",nickname)
				setCookie("token",token)
                showSuccess("注册成功！正在跳转...")
                setTimeout(function () {
                    location.href = '/'
                },2000)
            }else{
                var message = rd.message
                showWarning(message)
			}
        });
    }
}

/**
 * 设置管理员配置
 * @constructor
 */
function SubmitConfig() {
    $("#configFormBtn").prop("disabled", "disabled");
    var domain = $("#domain").val();
    var email = $("#email").val();
    var icp = $("#icp").val();
    if (domain == "") {
        $("#domain").focus();
        $("#domain").css("border", "1px solid red");
        showWarning("亲，请输入域名哦。")
        $("#configFormBtn").prop("disabled", "");
        return;
    }


    $("#email").css("border", "");
    $("#icp").css("border", "");
    if (!isposting()) {
        startPost();
        PostServerData("config/set", JSON.stringify({
            "domain" : domain,
            "email" : email,
            "icp": icp
        }), function(rd) {
            stopPost();
            $("#configFormBtn").prop("disabled", "");
            if (rd.code == 0) {
                showSuccess("修改成功！")
            }else{
                var message = rd.message
                showWarning(message)
            }
        });
    }
}

/**
 * 设置用户信息
 * @constructor
 */
function SubmitUserInfo() {
    $("#userInfoFormBtn").prop("disabled", "disabled");
    var nickname = $("#nickname").val();
    var mobile = $("#mobile").val();
    if (nickname == "") {
        $("#nickname").focus();
        $("#nickname").css("border", "1px solid red");
        showWarning("亲，请输入昵称哦。")
        $("#userInfoFormBtn").prop("disabled", "");
        return;
    }


    $("#nickname").css("border", "");
    $("#mobile").css("border", "");
    if (!isposting()) {
        startPost();
        PostServerData("user/userInfo", JSON.stringify({
            "nickname" : nickname,
            "mobile" : mobile
        }), function(rd) {
            stopPost();
            $("#userInfoFormBtn").prop("disabled", "");
            if (rd.code == 0) {
                setCookie("nickname",nickname)
                showSuccess("修改成功！")
            }else{
                var message = rd.message
                showWarning(message)
            }
        });
    }
}

/**
 * 设置密码
 * @constructor
 */
function SubmitPassword() {
    $("#resetPasswordFormBtn").prop("disabled", "disabled");
    var newPassword = $("#newPassword").val();
    if (newPassword == "") {
        $("#newPassword").focus();
        $("#newPassword").css("border", "1px solid red");
        showWarning("亲，请输入新密码哦。")
        $("#resetPasswordFormBtn").prop("disabled", "");
        return;
    }

    $("#newPassword").css("border", "");
    if (!isposting()) {
        startPost();
        PostServerData("user/resetPassword", JSON.stringify({
            "newPassword" : newPassword
        }), function(rd) {
            stopPost();
            $("#resetPasswordFormBtn").prop("disabled", "");
            if (rd.code == 0) {
                showSuccess("修改成功！")
            }else{
                var message = rd.message
                showWarning(message)
            }
        });
    }
}

/**
 * 获取apiKey
 * @constructor
 */
function SubmitApiKey() {
    $("#apiKeyFormBtn").prop("disabled", "disabled");
    $("#apiKey").val("正在生成...");
    if (!isposting()) {
        startPost();
        PostServerData("user/apiKey", JSON.stringify({
        }), function(rd) {
            stopPost();
            $("#apiKey").val("");
            $("#apiKeyFormBtn").prop("disabled", "");
            if (rd.code == 0) {
                $("#apiKey").val(rd.data);
                showSuccess( "api秘钥已生成！")
            }else{
                var message = rd.message
                showWarning(message)
            }
        });
    }
}

/**
 * 获取apiKey
 * @constructor
 */
function SubmitLogout() {
    if (!isposting()) {
        startPost();
        GetServerData("user/logout", function(rd) {
            stopPost();
            if (rd.code == 0) {
                setCookie("id","")
                setCookie("username","")
                setCookie("nickname","")
                setCookie("token","")
                location.href = "./"
            }else{
                var message = rd.message
                showWarning(message)
            }
        });
    }
}

function IsURL(urlString) {
	if (urlString.indexOf(".") > 0) {
		var idx = urlString.indexOf(".");
		var length = urlString.length;
		if (idx < (length - 1)) {
			return true;
		}
	} else
		return false;
}

function GetServerData(path, callbackss, callbackbs, callbackce, callbacker) {
    $.ajax({
        type : "GET",
        url : config.api+"/"+path,
        async : true,
        contentType:"application/json",
        dataType : "json",
        timeout : 20000,
        xhr: function(){
            var xhr = $.ajaxSettings.xhr();
            if (progressBar && xhr.upload) {
                xhr.upload.addEventListener("progress", progressBar, false);
                return xhr;
            }
        },
        beforeSend : function(XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader('access_token',getCookie("token"));
            if (callbackbs)
                callbackbs();
        },
        success : function(data) {
            if(data.code == 40101){
                showWarning("请先登录");
                setTimeout(function () {
                    location.href = "login.html"
                },2000)
            }else{
                if (callbackss)
                    callbackss(data);
            }


        },
        complete : function(XMLHttpRequest, textStatus) {

            console.log(textStatus)
            if(textStatus != 'success'){
                //showError("网络错误")
            }
            stopPost()
            if (callbackce)
                callbackce();
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            if (callbacker)
                callbacker();
        }
    });
}

function PostServerData(path, ddata, callbackss, callbackbs, callbackce, callbacker) {
	$.ajax({
		type : "POST",
		url : config.api+"/"+path,
		async : true,
        contentType:"application/json",
		dataType : "json",
		data : ddata,
		timeout : 20000,
		xhr: function(){
            var xhr = $.ajaxSettings.xhr();
            if (progressBar && xhr.upload) {
                xhr.upload.addEventListener("progress", progressBar, false);
                return xhr;
            }
		},
		beforeSend : function(XMLHttpRequest) {
			XMLHttpRequest.setRequestHeader('access_token',getCookie("token"));
			XMLHttpRequest.setRequestHeader('guestUid',getCookie("guestUid"));
			if (callbackbs)
				callbackbs();
		},
		success : function(data) {
		    if(data.code == 40101){
		        showWarning("请先登录");
		        setTimeout(function () {
                    location.href = "login.html"
                },2000)
            }else{
                if (callbackss)
                    callbackss(data);
            }


		},
		complete : function(XMLHttpRequest, textStatus) {
			console.log(textStatus)
			if(textStatus != 'success'){
				//showError("网络错误")
			}
            stopPost()
			if (callbackce)
				callbackce();
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
            if (callbacker)
				callbacker();
		}
	});
}
function fmoney(s) {
	s = parseFloat((s + "").replace(/[^\d\.-]/g, "")) + "";
	var l = s.split(".")[0].split("").reverse(),

	t = "";
	for (i = 0; i < l.length; i++) {
		t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
	}
	return t.split("").reverse().join("");
}
function cbChanged() {
	var k = $("#cb1").prop("checked");
	if (k) {
		$("#divContact").hide();
		$("#zname").val("");
		$("#zaddress").val("");
	} else {
		$("#divContact").show();
	}
}
function getUrlParam(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if (r != null)
		return decodeURIComponent(r[2]);
	return null;
}